package com.sise.rsc.security;


import com.sise.rsc.dao.RedisDao;
import com.sise.rsc.encoder.MyPasswordEncoder;
import com.sise.rsc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public static  PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(userService);
        provider.setPasswordEncoder(passwordEncoder);
        return  provider;
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()

                .antMatchers("/myLogin","/login","/doLogin","/customer/register").permitAll()
                .antMatchers("/html/*","/js/*","/css/*","/images/*","/layui/*","/font/*").permitAll()
                .antMatchers("/index").hasAnyRole("USER","KD","ADMIN")
                .antMatchers("/customer/*").hasRole("USER")
                .antMatchers("/courier/*").hasRole("KD")
                .antMatchers("/admin/*").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/myLogin").loginProcessingUrl("/doLogin").successForwardUrl("/index").permitAll()
                .and()
                .logout().logoutUrl("/logout").permitAll()
                .and()
                .csrf().disable().httpBasic();;
    }
}
